package com.guaoran.distributed.message.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author : guaoran
 * @Description : <br/>
 *  会话存在的机制
 *      事务性和非事务性
 * @date :2018/11/8 14:53
 */
public class Consumer {
    public static void main(String[] args) throws JMSException {
        ConnectionFactory connectionFactory =
                new ActiveMQConnectionFactory(CommonUtil.CONNECT_URL);
        Connection connection = null;
        try {
            //创建连接
            connection = connectionFactory.createConnection();
            connection.start();
            //创建session会话
            Session session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
            /**
             * Boolean.TRUE ：表示是事务性会话，只有当执行commit()时才会将告知mq已经消费消息，则删除该消息，否则，该消息会一直存在，
             * Boolean.FALSE: 表示是非事务性会话，不存在commit和rollback，都会将消息删除
             */

            //创建目的地
            Destination destination = session.createQueue("myQueue");
            MessageConsumer consumer = session.createConsumer(destination);
            for (int i = 0; i < 100; i++) {
                //用来接收消息
                TextMessage message = (TextMessage) consumer.receive();//如果当前没有消息，则会进行阻塞
                System.out.println(message.getText());
                session.commit();
            }
            session.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }finally {
            if(connection != null){
                connection.close();
            }
        }
    }
}
